#!/usr/bin/perl
use warnings;
use strict;
use feature 'state';


#将基因区域、外显子区域中，出现的重叠区域合并；
sub repetition{    		#方法；
	my ($gene,$exon);			#参数；
	($gene,$exon)=@_;			
	foreach my $file($gene,$exon){			#每一个文件；
		my @data;			#每个文件的私有二维数组；
		my $i=0;
		my @row;
		#input;
		open IN,"<","$file" or die "can't open file $file!\n";			#读入数据；
		while(<IN>){
			chomp;			#去掉空格；
			@row=();
			@row = split(/\s+/);		
			my ($chromosome,$type,$start,$end);			#四个字符；
			$chromosome = $row[0];
			$type = $row[1];
			$start = $row[2];
			$end = $row[3];
			if ($i != 0){
				if ($chromosome eq $data[$i-1][0]){		#染色体相同；
					if ($start =<$data[$i-1][3]){
						if ($end<$data[$i-1][3]){
							$row[2]=$data[$i-1][2];
							$row[3]=$data[$i-1][3];
						}else{
							$row[2]=$data[$i-1][2];
							#$row[3]=$data[$i][3];
						}
						#open "STDOUT",">>","${file}_regff.txt" or die "can't creat file ${file}_regff.txt!\n";
						#print "$data[$i-1][0]	$data[$i-1][1]	$data[$i-1][2]	$data[$i-1][3]\n";
						#close STDOUT;
					}else{			#输出上一个；
						open "STDOUT",">>","${file}_regff.txt" or die "can't creat file ${file}_regff.txt!\n";
						print "$data[$i-1][0]\t$data[$i-1][1]\t$data[$i-1][2]\t$data[$i-1][3]\n";
						close STDOUT;
					}
				}else{
					open "STDOUT",">>","${file}_regff.txt" or die "can't creat file ${file}_regff.txt!\n";
					print "$data[$i-1][0]	$data[$i-1][1]	$data[$i-1][2]	$data[$i-1][3]\n";
					close STDOUT;
				}
			}#else{
			#	open "STDOUT",">>","${file}_regff.txt" or die "can't creat file ${file}_regff.txt!\n";
			#	print "@row\n";
			#	close STDOUT;
			#}
			push @data,[@row];			#依次读入数据到二维数组中；
			$i++;			#记录行数；1、2、3；
		}
		close IN;
		#output again;
		open "STDOUT",">>","${file}_regff.txt" or die "can't creat file ${file}_regff.txt!\n";
		print "@row\n";
		close STDOUT;
	}
}
&repetition("gene.txt","exon.txt");			#调用方法及参数；
